import { defineStore } from 'pinia';
import { IAppSetting, ILocale, ILocalType } from '@/store/types';
import { appConfigSetting } from '@/settings/appConfigSetting';
import { store } from '@/store';
import { local } from '@/utils/storage';
import { setLocale } from '@/locales/useLocale';

const APP_SETTING = 'app_setting';
const appSetting = local.get<IAppSetting>(APP_SETTING, appConfigSetting);
export const useAppSettingStore = defineStore(APP_SETTING, {
  state: () => appSetting,
  getters: {
    getLocale(): ILocalType {
      return this.configLocal?.locale ?? ILocale.ZH_CN;
    },
    getCollapse(): boolean {
      return this.configMenu?.collapse;
    },
    getMobileMenuOpen(): boolean {
      return this.configMenu?.mobileMenuOpen;
    },
  },
  actions: {
    /**
     * 解决用户删除部分本地储存后读取配置问题
     * @description 初始化配置
     */
    initAppSetting() {
      this.$patch({
        ...appConfigSetting,
        ...this.$state,
      });
    },
    /**
     * 设置本地化
     */
    async setLocale(locale: ILocale) {
      if (locale == this.configLocal.locale) {
        return;
      }
      await setLocale(locale);
      this.configLocal.locale = locale;
    },
    /**
     * 转换侧边栏菜单折叠状态
     */
    toggleCollapse() {
      this.configMenu.collapse = !this.configMenu.collapse;
    },
    /**
     * 转换移动端侧边栏菜单折叠状态
     */
    toggleMobileMenuOpen() {
      this.configMenu.mobileMenuOpen = !this.configMenu.mobileMenuOpen;
    },
  },
});

/**
 * 在setup外使用store
 */
export const useAppSettingStoreWithOut = () => {
  return useAppSettingStore(store);
};

//添加订阅
const appSettingStore = useAppSettingStoreWithOut();
appSettingStore.$subscribe((mutation, state) => {
  local.set(mutation.storeId, JSON.stringify(state));
});
